const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const bodyParser = require('body-parser');

// 创建 Express 应用
const app = express();
const PORT = process.env.PORT || 3001;

// 基础中间件
app.use(helmet());
app.use(morgan('dev'));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 模拟数据
const mockData = {
  users: [
    { id: 1, username: 'test', email: 'test@example.com' }
  ],
  games: [
    {
      id: '1',
      level: 'easy',
      puzzle: Array(9).fill().map(() => Array(9).fill(0)),
      solution: Array(9).fill().map(() => Array(9).fill(0)),
      isComplete: false
    }
  ],
  leaderboard: {
    easy: Array(10).fill().map((_, i) => ({
      rank: i + 1,
      userId: i + 1,
      username: `player${i + 1}`,
      time: 300 + i * 30,
      score: 1000 - i * 50,
      date: new Date().toISOString()
    })),
    medium: Array(10).fill().map((_, i) => ({
      rank: i + 1,
      userId: i + 1,
      username: `player${i + 1}`,
      time: 500 + i * 30,
      score: 1500 - i * 50,
      date: new Date().toISOString()
    })),
    hard: Array(10).fill().map((_, i) => ({
      rank: i + 1,
      userId: i + 1,
      username: `player${i + 1}`,
      time: 800 + i * 30,
      score: 2000 - i * 50,
      date: new Date().toISOString()
    }))
  }
};

// 工具函数 - 生成模拟数独游戏
function generateMockSudoku(level) {
  // 创建一个简单的数独盘面用于演示
  const puzzle = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
  ];
  
  // 解决方案（简单填充）
  const solution = [
    [5, 3, 4, 6, 7, 8, 9, 1, 2],
    [6, 7, 2, 1, 9, 5, 3, 4, 8],
    [1, 9, 8, 3, 4, 2, 5, 6, 7],
    [8, 5, 9, 7, 6, 1, 4, 2, 3],
    [4, 2, 6, 8, 5, 3, 7, 9, 1],
    [7, 1, 3, 9, 2, 4, 8, 5, 6],
    [9, 6, 1, 5, 3, 7, 2, 8, 4],
    [2, 8, 7, 4, 1, 9, 6, 3, 5],
    [3, 4, 5, 2, 8, 6, 1, 7, 9]
  ];
  
  return {
    id: Math.random().toString(36).substring(2, 10),
    level,
    puzzle,
    solution
  };
}

// API 路由 - 用户
app.post('/api/users/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'test' && password === 'password') {
    res.json({
      code: 0,
      message: '登录成功',
      data: {
        id: 1,
        username: 'test',
        token: 'mock-token-123456'
      }
    });
  } else {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误'
    });
  }
});

app.post('/api/users/register', (req, res) => {
  const { username, password } = req.body;
  res.json({
    code: 0,
    message: '注册成功',
    data: {
      id: mockData.users.length + 1,
      username,
      token: 'mock-token-' + Math.random().toString(36).substring(2, 10)
    }
  });
});

app.post('/api/users/wechat-login', (req, res) => {
  res.json({
    code: 0,
    message: '登录成功',
    data: {
      id: 2,
      username: 'wechat_user',
      token: 'mock-wechat-token-' + Math.random().toString(36).substring(2, 10)
    }
  });
});

app.get('/api/users/profile', (req, res) => {
  res.json({
    code: 0,
    data: {
      id: 1,
      username: 'test',
      email: 'test@example.com',
      stats: {
        gamesPlayed: 10,
        gamesWon: 8,
        bestTime: 120,
        averageTime: 180
      }
    }
  });
});

// API 路由 - 游戏
app.get('/api/games/new', (req, res) => {
  const { level = 'easy' } = req.query;
  const game = generateMockSudoku(level);
  mockData.games.push(game);
  
  res.json({
    code: 0,
    message: '创建游戏成功',
    data: game
  });
});

app.post('/api/games/save', (req, res) => {
  const { gameId } = req.body;
  res.json({
    code: 0,
    message: '保存游戏成功',
    data: { id: gameId || 'game-' + Math.random().toString(36).substring(2, 10) }
  });
});

app.get('/api/games/saved', (req, res) => {
  res.json({
    code: 0,
    message: '获取保存的游戏成功',
    data: mockData.games.slice(0, 3)
  });
});

app.post('/api/games/check', (req, res) => {
  res.json({
    code: 0,
    data: {
      completed: true,
      correct: true,
      score: 850,
      time: req.body.time || 1200
    }
  });
});

app.post('/api/games/hint', (req, res) => {
  const { row, col } = req.body;
  res.json({
    code: 0,
    message: '获取提示成功',
    data: {
      row,
      col,
      value: Math.floor(Math.random() * 9) + 1
    }
  });
});

app.get('/api/games/:id', (req, res) => {
  const { id } = req.params;
  const game = mockData.games.find(g => g.id === id) || generateMockSudoku('medium');
  
  res.json({
    code: 0,
    message: '获取游戏详情成功',
    data: game
  });
});

// API 路由 - 排行榜
app.get('/api/leaderboard/global', (req, res) => {
  const { level = 'easy' } = req.query;
  res.json({
    code: 0,
    message: '获取排行榜成功',
    data: {
      total: mockData.leaderboard[level].length,
      rows: mockData.leaderboard[level]
    }
  });
});

app.get('/api/leaderboard/difficulty/:level', (req, res) => {
  const { level } = req.params;
  const validLevel = ['easy', 'medium', 'hard'].includes(level) ? level : 'easy';
  
  res.json({
    code: 0,
    message: '获取排行榜成功',
    data: {
      difficulty: validLevel,
      total: mockData.leaderboard[validLevel].length,
      rows: mockData.leaderboard[validLevel]
    }
  });
});

app.get('/api/leaderboard/rank', (req, res) => {
  res.json({
    code: 0,
    message: '获取用户排名成功',
    data: {
      userId: 1,
      username: 'test',
      easy: {
        rank: 5,
        bestTime: 180
      },
      medium: {
        rank: 7,
        bestTime: 350
      },
      hard: {
        rank: 10,
        bestTime: 600
      }
    }
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok', message: '服务运行正常' });
});

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({ error: '路由不存在' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`模拟后端服务器运行在 http://localhost:${PORT}`);
  console.log(`可以访问 http://localhost:${PORT}/health 测试服务器是否正常运行`);
});

module.exports = app;
